package com.treasure.mall.zbqmallmanager.base.security;


import com.treasure.mall.biz.service.core.auth.SystemService;
import com.treasure.mall.biz.service.core.user.MerchantService;
import com.treasure.mall.zbq.common.ienum.auth.RoleEnum;
import lombok.Setter;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;


/**
 * @author allan
 * @date 10/11/2017
 */
@Setter
public class StAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
    private PasswordEncoder passwordEncoder;

    private SystemService systemService;
    private MerchantService merchantService;

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authenticationToken) throws AuthenticationException {

        if (!userDetails.isEnabled()) {
            throw new LockedException("账户已锁定");
        }

        //密码校验
        String presentedPassword = userDetails.getPassword();
        if (!passwordEncoder.matches((String) authenticationToken.getCredentials(), presentedPassword)) {
            throw new BadCredentialsException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badCredentials",
                    "Bad credentials"));
        }
    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException {
        StAuthenticationToken authenticationToken = (StAuthenticationToken) usernamePasswordAuthenticationToken;


        UserDetails userDetails;
        try {
            if (authenticationToken.getRoleEnum() == RoleEnum.MERCHANT) {
                userDetails = merchantService.loadUserByUsername(username);
            } else {
                userDetails = systemService.loadUserByUsername(username);
            }
        } catch (Exception e) {
            throw new UsernameNotFoundException("不存在该帐号", e);
        }

        if (userDetails == null) {
            throw new UsernameNotFoundException("不存在该帐号");
        }
        return userDetails;
    }
}
